import { Component, OnInit } from '@angular/core';
import { UserService } from '@/service/user.service'
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
  username: string = ''
  password: string = ''
  hasError: boolean = false
  errorMessage: string = ''

  constructor(private user: UserService, private router: Router) { }

  ngOnInit(): void {
  }

  tryLogin() {
    this.user.tryLogin(this.username, this.password).subscribe(el => {
      if (el.flag) {
        this.hasError = false
        this.errorMessage = ""
        // const data = el.data as UserCache
        // this.store.dispatch(saveUserCacheAction({ loginuser: data }));

        this.router.navigateByUrl("layout/home")
      } else {
        this.hasError = true
        this.errorMessage = el.message
      }
    })
  }

  onLoginClicked() {
    if (this.username.length == 0) {
      this.hasError = true
      this.errorMessage = "请填写用户名"
      return
    }
    if (this.password.length == 0) {
      this.hasError = true
      this.errorMessage = "请填写密码"
      return
    }

    this.hasError = false
    this.errorMessage = ''

    this.tryLogin();
  }

  loginByDingTalk() {
    this.user.getDingtalkURL().subscribe(el => {
      if (el && el.url) {
        window.location.replace(el.url);
      }
    })
  }
}
